package com.manage.cloud.customize;

import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证失败消息自定义返回
 * @author zhangqing
 */
@Component
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {

    @SneakyThrows
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        System.out.println(authException.getMessage());
        try {
            response.getWriter().write(JSONUtil.toJsonPrettyStr("{messgae:认证失败,code:401}"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
